<?php
define("ENTER",chr(13).chr(10));
class Files
{
	function Files()
	{
	}
	
	public function copyDirVSfiles($source, $destination)
	{
	    $result = true;
	    if(!is_dir($source)){
	        return false;
	    }
	    if(!is_dir($destination)){
	        if(!mkdir($destination, 0700)){
	            trigger_error('Invalid Parameter', E_USER_ERROR);
	        }
	    }
	
	    $handle = opendir($source);
	    while(($file = readdir($handle)) !== false){
	        if($file != '.' && $file != '..'){
	            $src = $source . DIRECTORY_SEPARATOR . $file;
	            $dtn = $destination . DIRECTORY_SEPARATOR . $file;
	            if(is_dir($src)){
	                $this->copyDirVSfiles($src, $dtn);
	            }else{
	                if(! copy($src, $dtn)){
	                    $result = false;
	                    break;
	                }
	            }
	        }
	    }
	    closedir($handle);
	    return $result;
	}

	public function copyDir($source, $destination)
	{
	    $result = true;
	    if(!is_dir($source)){
	        return false;
	    }
	    if(!is_dir($destination)){
	        if(!mkdir($destination, 0700)){
	            trigger_error('Invalid Parameter', E_USER_ERROR);
	        }
	    }
	
	    $handle = opendir($source);
	    while(($file = readdir($handle)) !== false){
	        if($file != '.' && $file != '..'){
	            $src = $source . DIRECTORY_SEPARATOR . $file;
	            $dtn = $destination . DIRECTORY_SEPARATOR . $file;
	            if(is_dir($src)){
	                $this->copyDirVSfiles($src, $dtn);
	            }
	        }
	    }
	    closedir($handle);
	    return $result;
	}

	public function copyFiles($source, $destination)
	{
		$result = true;
	    if(!is_dir($source)){
	        return $result;
	    }
	    if(!is_dir($destination)){
	        if(!mkdir($destination, 0700)){
	            trigger_error('Invalid Parameter', E_USER_ERROR);
	        }
	    }
	
	    $handle = opendir($source);
	    while(($file = readdir($handle)) !== false){
	        if($file != '.' && $file != '..'){
	            $src = $source . DIRECTORY_SEPARATOR . $file;
	            $dtn = $destination . DIRECTORY_SEPARATOR . $file;
	            if(!is_dir($src)){
		            if(! copy($src, $dtn)){
		                 $result = false;
		                 break;
		            }
	            }
	        }
	    }
	    
	    closedir($handle);
	    return $result;
	}
	
	public function moveFiles($source, $destination)
	{
		$result = true;
	    if(!is_dir($source)){
	        return $result;
	    }
	    if(!is_dir($destination)){
	        if(!mkdir($destination, 0700)){
	            trigger_error('Invalid Parameter', E_USER_ERROR);
	        }
	    }
	
	    $handle = opendir($source);
	    while(($file = readdir($handle)) !== false){
	        if($file != '.' && $file != '..'){
	            $src = $source . DIRECTORY_SEPARATOR . $file;
	            $dtn = $destination . DIRECTORY_SEPARATOR . $file;
	            if(!is_dir($src)){
		            if(! copy($src, $dtn)){
		                 $result = false;
		                 break;
		            }
	            }
	        }
	    }
	    
	    closedir($handle);
	    $this->clearDir($source);
	    
	    return $result;
	}
	
	public function listFileName($dir)
	{
		$arrReturn = array();
		
		if(!is_dir($dir)){
	        return $arrReturn;
	    }
	    
	    $handle = opendir($dir);
	    while(($file = readdir($handle)) !== false){
       	 	if(is_file($dir. DIRECTORY_SEPARATOR . $file)){
	        	$arrReturn[] = $file;
	        }
	    }
	    
	    return $arrReturn;
	}

	public function copyFilesFilter($source, $destination, $strFilterType)
	{
		$result = true;
	    if(!is_dir($source)){
	        return $result;
	    }
	    if(!is_dir($destination)){
	        if(!mkdir($destination, 0700)){
	            trigger_error('Invalid Parameter', E_USER_ERROR);
	        }
	    }
	
	    $handle = opendir($source);
	    while(($file = readdir($handle)) !== false){
	        if($file != '.' && $file != '..'){
	            $src = $source . DIRECTORY_SEPARATOR . $file;
	            $dtn = $destination . DIRECTORY_SEPARATOR . $file;
	            if(!is_dir($src) AND strripos($src, $strFilterType) != strlen($src) - strlen($strFilterType)){
		            if(! copy($src, $dtn)){
		                 $result = false;
		                 break;
		            }
	            }
	        }
	    }
	    closedir($handle);
	    return $result;
	}
	public function clearDir($dirName)
	{
	    $result = true;
	    if(! is_dir($dirName)){
	        return $result;
	    }
	
	    $handle = opendir($dirName);
	    while(($file = readdir($handle)) !== false){
	        if($file != '.' && $file != '..'){
	            $dir = $dirName . DIRECTORY_SEPARATOR . $file;
	            is_dir($dir) ? $this->removeDir($dir) : unlink($dir);
	        }
	    }
	    closedir($handle);
	    return $result;
	}
	
	public function removeDir($dirName)
	{
	    $result = false;
	    if(! is_dir($dirName)){
	        return $result;
	    }
	
	    $handle = opendir($dirName);
	    while(($file = readdir($handle)) !== false){
	        if($file != '.' && $file != '..'){
	            $dir = $dirName . DIRECTORY_SEPARATOR . $file;
	            is_dir($dir) ? $this->removeDir($dir) : unlink($dir);
	        }
	    }
	    closedir($handle);
	    return  rmdir($dirName) ? true : false;
	}
	
	public function createCFGfileET($strSiteDirName, $siteID, $templateid)
	{
		$fp = fopen($_SERVER['DOCUMENT_ROOT']."/sites/" . $strSiteDirName . "/config.inc.php", "w");
		fputs($fp, "<?php" . ENTER);

		fputs($fp, "define('SITE_ID', '". $siteID . ENTER);
		fputs($fp, "define('TEMPLATE_ID', '". $templateid . ENTER);

		
		fputs($fp, "define('TEMPLATE_DIR', '". $_SERVER['DOCUMENT_ROOT']."/sites/" . $strSiteDirName . "/templates/');" . ENTER);
		fputs($fp, "define('COMPILE_DIR', '". $_SERVER['DOCUMENT_ROOT']."/sites/" . $strSiteDirName . "/templates_c/');" . ENTER);
		fputs($fp, "define('CACHE_DIR', '". $_SERVER['DOCUMENT_ROOT']."/sites/" . $strSiteDirName . "/cache/');" . ENTER);
		
		fputs($fp, "?>" . ENTER);
	}
	
	public function arrSplitContent($strContent, $iSplitLength = 10)
	{  
		$arrReturn = array();
		$iContentLen = strlen($strContent);
		if ($iContentLen > $iSplitLength){
			$i		= 0;
			$iStart = 0;
			$iEnd = $iSplitLength;
			while($i < $iContentLen){
				for($i = $iStart; $i < $iEnd; $i++) 
					if (ord($strContent[$i]) > 128)
						$i++; 
				$arrReturn[] = substr($strContent, $iStart, $iSplitLength);
				
				$iStart = $iEnd;
				$iEnd = $iEnd + $iSplitLength;
				if($iEnd > $iContentLen)
					$iEnd = $iContentLen;
			}
		} 
		return $arrReturn; 
	}
	
	public function createDataFile($strPathDir, $arrContent)
	{
		$i = 0;
		foreach ($arrContent as $value){
			$fp = fopen($strPathDir . '/'. $i. ".dat", "w");
			if($fp){
				fputs($fp, $value);
				fclose($fp);
			}
		}
	}
	
	public static function getDirById($id)
	{
		$strPathPosFromEnd_3_4 = '';
		$strPathPosFromEND_1_2 = '';
		switch (strlen($id)){
			case 1: $strPathPosFromEND_1_2 = "0". $id; $strPathPosFromEnd_3_4 = "00"; break;
			case 2: $strPathPosFromEND_1_2 = $id; $strPathPosFromEnd_3_4 = "00"; break;
			case 3: $strPathPosFromEND_1_2 = substr($id, -2, 2); $strPathPosFromEnd_3_4 = "0" . substr($id, -3, 1); break;
			default:$strPathPosFromEND_1_2 = substr($id, -2, 2); $strPathPosFromEnd_3_4 = substr($id, -4, 2); break;
		}
		
		return ($id % 10) . '/' . $strPathPosFromEnd_3_4 . '/' . $strPathPosFromEND_1_2;
	}
	
	public static function getCustomDirById($id, $separator)
	{
		$strPathPosFromEnd_3_4 = '';
		$strPathPosFromEND_1_2 = '';
		switch (strlen($id)){
			case 1: $strPathPosFromEND_1_2 = "0". $id; $strPathPosFromEnd_3_4 = "00"; break;
			case 2: $strPathPosFromEND_1_2 = $id; $strPathPosFromEnd_3_4 = "00"; break;
			case 3: $strPathPosFromEND_1_2 = substr($id, -2, 2); $strPathPosFromEnd_3_4 = "0" . substr($id, -3, 1); break;
			default:$strPathPosFromEND_1_2 = substr($id, -2, 2); $strPathPosFromEnd_3_4 = substr($id, -4, 2); break;
		}
		
		return ($id % 10) . $separator . $strPathPosFromEnd_3_4 . $separator . $strPathPosFromEND_1_2;
	}
	
	public function getAbsolutePathById($absolutePath, $id)
	{
		$strPath = $absolutePath . $this->getDirByID($id);
	 	
		$this->createFolder($strPath);
		
	    return $strPath;
	}
	
	public function getFullPathByID($absolutePath, $id, $fileName)
	{
		$strPath = $absolutePath . $this->getDirByID($id);
	 	
		$this->createFolder($strPath);
		
	    return $strPath . '/' . $fileName;
	}
	
	public function createFolder($path)
	{
	   	if (!file_exists($path)) {
	   		$this->createFolder(dirname($path));
	
	    	mkdir($path, 0777);
	   	}
	}
	
	function Resize($Filename,$Thumbnail,$WIDTH,$HEIGHT)
	{
         $image = $Filename;
         $thumbnail = $Thumbnail;
         $imagesize = getimagesize($image);
         $fwidth = $imagesize[0];
         $fheight = $imagesize[1];
               
          if($fheight <= $fwidth){
               $percentage = round(($WIDTH/$fwidth) * 100);
               $newwidth  = round(($fwidth  * $percentage)/100);
               $newheight = round(($fheight * $percentage)/100);
          }elseif($fheight > $fwidth){
               $percentage = round(($HEIGHT/$fheight) * 100);
               $newwidth  = round(($fwidth  * $percentage)/100);
               $newheight = round(($fheight * $percentage)/100);
          }else{
               $percentage = round(($fwidth/$WIDTH) * 100);
               $newwidth  = round(($fwidth  * $percentage)/100);
               $newheight = round(($fheight * $percentage)/100);
          }

          $destImage = imagecreatetruecolor($newwidth,$newheight) or die($Filename.' - '.$newwidth.':'.$newheight);
          $type = strtolower(substr($Filename,-3));
          switch($type){
               case 'gif':
                    $srcImage = ImageCreateFromGif($image);
                    ImageCopyResized($destImage, $srcImage, 0,0, 0, 0, $newwidth, $newheight, imagesx($srcImage), imagesy($srcImage));
                    ImageGif($destImage,$thumbnail);
                    break;
               case 'jpg':
                    $srcImage = ImageCreateFromJPEG($image);
                    ImageCopyResized($destImage, $srcImage, 0,0, 0, 0, $newwidth, $newheight, imagesx($srcImage), imagesy($srcImage));
                    ImageJPEG($destImage,$thumbnail);
                    break;
                case 'png':
                    $srcImage = ImageCreateFromPNG($image);
                    ImageCopyResized($destImage, $srcImage, 0,0, 0, 0, $newwidth, $newheight, imagesx($srcImage), imagesy($srcImage));
                    ImagePNG($destImage,$thumbnail);
                    break;
           }
           
           //free the memory used for the images
           ImageDestroy($srcImage);
           ImageDestroy($destImage);
               
           if(file_exists($thumbnail)){
                return true;
           }else{
                return false;
           }
     }
     
    public function mk_dir($dirString, $initDir="./")
    {  
		  $dir = explode("/", $dirString);
		  if(substr($initDir,-1) != "/" && $initDir != "")  
		  	$initDir .= $initDir."/";  
		   
		  for($i=0; $i <= count($dir)-1; $i++){  
		  	$initDir .= $dir[$i] . "/";
		  	
		  	if(!file_exists($initDir) && count($dir) > 0)
		  		mkdir($initDir);
				
		  		$dir = $initDir;
		  };
		  
		  return $dir;
  	}
  	
  	public function zip($zipFile, $customDir = '')
  	{
  		$zip = zip_open($zipFile);
  		
  		$returnDir = '';
  		
  		if($zip){
  			if(empty($customDir))
  				$outDir = dirname($zipFile) . '/';
  			else
  				$outDir = $customDir;
  				
  			while($zip_entry = zip_read($zip)){
  				if(substr(zip_entry_name($zip_entry),-1) != "/" && zip_entry_open($zip, $zip_entry, "r")) {  
 		  			if (!file_exists(dirname(zip_entry_name($zip_entry)))){  
					  	$this->mk_dir(zip_entry_name($zip_entry));  
					}
					
					$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));  
					$fout = fopen($outDir . zip_entry_name($zip_entry),"w");
					
					fwrite($fout,$buf);  
					//echo "extract : ".zip_entry_name($zip_entry)."\n";  
					 
					zip_entry_close($zip_entry);  
				} else {  
				    $returnDir = $this->mk_dir(zip_entry_name($zip_entry), $outDir);
		 		}		 
		    }
		 	
		    zip_close($zip);
		}
		
		return $returnDir;
  	}
  	
  	public function removeZipExtractDir($zipFile, $customDir = '')
  	{
  		$zip = zip_open($zipFile);
  		
  		if($zip){
  			if(empty($customDir))
  				$outDir = dirname($zipFile) . '/';
  			else
  				$outDir = $customDir;
  				
  			while($zip_entry = zip_read($zip)){
  				if(is_dir(zip_entry_name($zip_entry))){
  					$this->removeDir($outDir.zip_entry_name($zip_entry));
  					//echo 'remove dir :'.$outDir.zip_entry_name($zip_entry).'<br>';
  				}else{
  					if(file_exists($outDir.zip_entry_name($zip_entry)))
  						unlink($outDir.zip_entry_name($zip_entry));
  					//echo 'remove file :'.$outDir.zip_entry_name($zip_entry).'<br>';
  				}	 
		    }
		 	
		    zip_close($zip);
		}
  	}
  	
	public function getZipExtractDir($zipFile, $customDir = '')
  	{
  		$zip = zip_open($zipFile);
	  		
		$returnDir = '';
					  		
  		if($zip){
  			if(empty($customDir))
  				$outDir = dirname($zipFile) . '/';
  			else
  				$outDir = $customDir;
  				
  			if($zip_entry = zip_read($zip)){
  				if(is_dir(zip_entry_name($zip_entry))){
  					$returnDir = $outDir.zip_entry_name($zip_entry);
  				}	 
		    }
					 	
		    zip_close($zip);
		}
		
		return $returnDir;
  	}
}


?>
